#!/bin/bash
# dependent: curl tar 
#
# LuCI Tiny File Manager
# Author: muink
# Github: https://github.com/muink/luci-app-tinyfilemanager
#

# PKGInfo
REPOURL='https://github.com/prasathmani/tinyfilemanager'
PKGNAME='tinyfilemanager'
VERSION="$1"; VERSION="${VERSION:=2.6}"
#
PKG_DIR=$PKGNAME-$VERSION
REF_DIR="assets"
#
INDEXPHP="tinyfilemanager.php"
#CFGSAMPl="config-sample.php"
LANGFILE="translation.json"


WORKDIR="/www/$PKGNAME"
mkdir -p "$WORKDIR" 2>/dev/null
cd $WORKDIR

if [ "$(uci -q get $PKGNAME.@main[0].proxy_enabled)" == "1" ]; then
    export ALL_PROXY=$(uci -q get $PKGNAME.@main[0].proxy_protocol)://$(uci -q get $PKGNAME.@main[0].proxy_server)
fi



# Clear Old version
rm -rf *

# Download Repository
grep -qE "^(master|main)$" <<< "$VERSION" && refs=heads || refs=tags
curl -sSL https://codeload.github.com/prasathmani/tinyfilemanager/tar.gz/refs/$refs/$VERSION | tar -xvz -C /tmp

# Version Check
if   [ -z "$(sed -En "/^\\\$external = array\(/,/^\);/p" /tmp/$PKG_DIR/$INDEXPHP)" ]; then
    online=y ver_cc=old # <= 2.5.3
elif [ -n "$(sed -En "/^\\\$external = array\(/,/^\);/{s,^(.+=\")(http(s)?://.+/)([^/]+\.(css|js))(\".+),\4,p}" /tmp/$PKG_DIR/$INDEXPHP)" ]; then
    online=y ver_cc=master
else
    online=n ver_cc=offline
fi
[ "$online" = "y" ] && {

# Preprocessing
sed -Ei "/<link rel=\"(preconnect|dns-prefetch)\"/d" /tmp/$PKG_DIR/$INDEXPHP
[ "$ver_cc" = "old" ] && {
    FM_HIGHLIGHTJS_STYLE=$(sed -En "s|^\\\$highlightjs_style = *'([^']*)';|\1|p" /tmp/$PKG_DIR/$INDEXPHP)
    sed -i "s|<?php echo FM_HIGHLIGHTJS_STYLE ?>|\$FM_HIGHLIGHTJS_STYLE|g" /tmp/$PKG_DIR/$INDEXPHP
}
[ "$ver_cc" = "master" ] && {
    __highlightjs_style=$(sed -En "s|^\\\$highlightjs_style = *'([^']*)';|\1|p" /tmp/$PKG_DIR/$INDEXPHP)
    sed -i "s|' . \$highlightjs_style . '|\$__highlightjs_style|" /tmp/$PKG_DIR/$INDEXPHP
}

# Download CDN Used
mkdir -p "$REF_DIR" 2>/dev/null
[ "$ver_cc" = "old" ] && refurl=($(sed -En "s,^.+=\"(https?://.+\.(css|js))\".+,\1,p" /tmp/$PKG_DIR/$INDEXPHP | sort -u ))
[ "$ver_cc" = "master" ] && refurl=($(sed -En "/^\\\$external /,/^\);/{s,^.+=\"(http(s)?://.+\.(css|js))\".+,\1, p}" /tmp/$PKG_DIR/$INDEXPHP | sort -u ))
ref=
url=
out=
path=

# \.(css|js) main ref
for _i in $(seq 0 1 $[ ${#refurl[@]} -1 ]); do
    eval "url=${refurl[$_i]}"
    out=${url##*/}
    path="$REF_DIR/${url#http*://}"

    mkdir -p "${path%/*}" 2>/dev/null
    curl -sSLo $out $url
    mv -f $out "${path%/*}"
done

ref=$(for _p in $(find * -type f); do \
        sed -E "s/(,|;)/\1\n/g" $_p | grep -E "\burl\([^\)]+\)" | grep -Ev "\burl\(\"data:image" >/dev/null; \
        [ "$?" == "0" ] && echo $_p; \
    done)

# ref of main ref
for _i in $ref; do
    suburl=($(sed -E "s/(,|;)/\1\n/g" $_i | grep -E "\burl\([^\)]+\)" | grep -Ev "\burl\(\"data:image" | sed -En "s|^[^']+'([^']+)'.+|\1| p"))
    hosturl=$(for _ in "${refurl[@]}"; do grep "${_i##*/}" <<< "$_"; done)

    for _j in $(seq 0 1 $[ ${#suburl[@]} -1 ]); do
        url="${suburl[$_j]}"
        out=${url%%\?*}
        path="$REF_DIR/${hosturl#http*://}"

        mkdir -p "${path%/*}/${out%/*}" 2>/dev/null
        curl -sSLo ${out##*/} "${hosturl%/*}/$url"
        mv -f ${out##*/} "${path%/*}/$out"
    done
done

# Post-processing
[ "$ver_cc" = "old" ] && sed -i "s|\$FM_HIGHLIGHTJS_STYLE|<?php echo FM_HIGHLIGHTJS_STYLE ?>|g" /tmp/$PKG_DIR/$INDEXPHP
[ "$ver_cc" = "master" ] && sed -i "s|\$__highlightjs_style|' . \$highlightjs_style . '|" /tmp/$PKG_DIR/$INDEXPHP

# Hotfix

# Migrating to Local Reference
sed -Ei "s,^(.+=\")https?://(.+\.(css|js))(\".+),\1$REF_DIR/\2\4," /tmp/$PKG_DIR/$INDEXPHP

}

# FixED
[ "$ver_cc" = "master" ] || sed -Ei "/^if \(\\\$use_auth\) \{/,/^}/{/\/\/ Logging In/,/\/\/ Form/{s|(fm_redirect\().+|\1FM_SELF_URL);|g}}" /tmp/$PKG_DIR/$INDEXPHP

# Clean up and Done
[ -d "/tmp/$PKG_DIR/$REF_DIR" ] && cp -rf "/tmp/$PKG_DIR/$REF_DIR" .
mv -f /tmp/$PKG_DIR/$INDEXPHP ./index.php
#mv -f /tmp/$PKG_DIR/$CFGSAMPl .
mv -f /tmp/$PKG_DIR/$LANGFILE .
find * -type d -exec chmod 755 {} \;
find * -type f -exec chmod 644 {} \;
[ ! -d /www/tinyfilemanager/rootfs ] && ln -s / /www/tinyfilemanager/rootfs
/etc/init.d/tinyfilemanager start



#$(INSTALL_DIR) $(1)/usr/libexec
#$(INSTALL_DIR) $(1)/www/$PKGNAME
#$(INSTALL_BIN) run.sh $(1)/usr/libexec/$PKGNAME
#$(CP) $PKG_DIR/$INDEXPHP $(1)/www/$PKGNAME/index.php
#$(CP) $PKG_DIR/$CFGSAMPl $(1)/www/$PKGNAME/$CFGSAMPl
#$(CP) $PKG_DIR/$LANGFILE $(1)/www/$PKGNAME/$LANGFILE
#$(CP) --parents -rf $REF_DIR/ $(1)/www/$PKGNAME/
